﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using Process.API.Application.Command.Show;
using Process.Domain;
using Process.ErrorCode;
using Process.Infrastructure.Interface;

namespace Process.API.Application.Handler.Show
{
    public class ProductionOrdersHandler : IRequestHandler<ProductionOrdersCommand, APIResult<APIPaging<List<ProductionOrders>>>>
    {
        IBaseRepository<ProductionOrders> proRep;

        public ProductionOrdersHandler(IBaseRepository<ProductionOrders> proRep)
        {
            this.proRep = proRep;
        }

        public async Task<APIResult<APIPaging<List<ProductionOrders>>>> Handle(ProductionOrdersCommand request, CancellationToken cancellationToken)
        {
           
            var m = await proRep.GetAll().Where(a => !a.IsDel).ToListAsync();
            if (!string.IsNullOrEmpty(request.ProductionOrdersCode))
            {
                m = m.Where(a => a.ProductionOrdersCode.Contains(request.ProductionOrdersCode)).ToList();
            }
            if (!string.IsNullOrEmpty(request.ProductionOrdersName))
            {
                m = m.Where(a => a.ProductionOrdersName.Contains(request.ProductionOrdersName)).ToList();
            }
            if (!string.IsNullOrEmpty(request.ProductName))
            {
                m = m.Where(a => a.ProductionOrdersCode.Contains(request.ProductName)).ToList();
            }
            if (request.State != null)
            {
                m = m.Where(a => a.State == request.State).ToList();
            }



            int count = m.Count();
            int pount = (int)Math.Ceiling(count * 1.0 / request.PageSize);
            m = m.OrderByDescending(a => a.ProductionOrdersId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();


            return new APIResult<APIPaging<List<ProductionOrders>>>
            {
                Code = APIEnum.Ok,
                Message = "生产工单显示成功",
                Data =new APIPaging<List<ProductionOrders>>
                {
                    TotalCount=count,
                    TotalPage=pount,
                    PageDatas=m
                }
            };

        }
    }
}
